package com.cssy.yd.logic.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.byd.acegiext.domain.User;
import com.cssy.yd.logic.dao.LogicFkDAO;
import com.cssy.yd.logic.dao.LogicFkItemDAO;
import com.cssy.yd.logic.dao.LogicPoWareDAO;
import com.cssy.yd.logic.entity.LogicPoWareDO;
import com.cssy.yd.logic.entity.LogicFkDO;
import com.cssy.yd.logic.entity.LogicFkItemDO;
import com.cssy.yd.logic.service.ILogicFkService;
import com.plat.exception.SyBaseException;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.DateUtils;
import com.plat.util.GlobalResLoader;
import com.plat.util.IDCodeTypeUtil;
import com.plat.util.SessionUtil;
import com.yuendong.sy.exception.SyCodeException;
import com.yuendong.sy.po.code.SyCode;
import com.yuendong.sy.service.code.SyCodeType;
import com.yuendong.sy.service.code.impl.SyCodeService;

@Service("logicFkService")
public class LogicFkServiceImpl implements ILogicFkService {
	@Resource(name = "logicFkDAO")
	private LogicFkDAO logicFkDAO;

	@Resource(name = "logicFkItemDAO")
	private LogicFkItemDAO logicFkItemDAO;

	@Resource(name = "syCodeService")
	private SyCodeService syCodeService;
	
	@Resource(name = "logicPoWareDAO")
	private LogicPoWareDAO logicPoWareDAO;
	
	@Override
	public SearchResult findListByExample(SearchConditions scs)
			throws SyBaseException {
		SearchResult rs = new SearchResult(scs);
		List<LogicFkDO> list = logicFkDAO.find(scs);
		rs.setRecordCount(logicFkDAO.count(scs));
		rs.setResults(list);
		return rs;
	}

	@Override
	public Integer delete(String id, User user) throws SyBaseException {
		Integer i = logicFkDAO.deleteLogicFkDOByPrimaryKey(id);
		return i;
	}

	@Override
	public Integer update(LogicFkDO t, User user) throws SyBaseException {
		t.setDuuser(user.getName());
		t.setDutime(new Date());
		return logicFkDAO.updateLogicFkDO(t);
	}

	@Override
	public LogicFkDO save(LogicFkDO t, User user) throws SyBaseException {
		t.setDcruser(user.getName());
		t.setDctime(new Date());
		t.setId(IDCodeTypeUtil.getId());
		logicFkDAO.insertLogicFkDO(t);
		return t;
	}

	@Override
	public LogicFkDO findListById(String id) throws SyBaseException {
		return logicFkDAO.findLogicFkDOByPrimaryKey(id);
	}

	@Override
	public SearchResult findItemListByExample(SearchConditions scs)
			throws SyBaseException {
		SearchResult rs = new SearchResult(scs);
		List<LogicFkItemDO> list = logicFkItemDAO.find(scs);
		rs.setRecordCount(logicFkItemDAO.count(scs));
		rs.setResults(list);
		return rs;
	}

	@Override
	public Integer deleteItem(String id) throws SyBaseException {
		Integer i = logicFkItemDAO.deleteLogicFkItemDOByPrimaryKey(id);
		return i;
	}

	@Override
	public Integer updateItem(LogicFkItemDO t) throws SyBaseException {
		return logicFkItemDAO.updateLogicFkItemDO(t);
	}

	@Override
	public LogicFkItemDO saveItem(LogicFkItemDO t) throws SyBaseException {
		t.setId(IDCodeTypeUtil.getId());
		logicFkItemDAO.insertLogicFkItemDO(t);
		return t;
	}

	@Override
	public List<LogicFkItemDO> findItemListByfkid(String fkid)
			throws SyBaseException {

		return logicFkItemDAO.finditembyfkid(fkid);
	}

	@Override
	public Double findLastedDOByExample(SearchConditions scs)
			throws SyBaseException {
		return logicFkDAO.findLastedDOByOricode(scs);
	}

	@Override
	public LogicFkItemDO findItemListById(String id) throws SyBaseException {
		return logicFkItemDAO.findLogicFkItemDOByPrimaryKey(id);
	}

	@Override
	public void fksave(HttpServletRequest request, LogicFkDO curAP)
			throws SyBaseException, SyCodeException {
		try {//新增草稿
			String fkDate = request.getParameter("fkDate");
			String itemdata = request.getParameter("itemdata");	
 			List<LogicFkItemDO> itemlist = JSONArray.parseArray(itemdata, LogicFkItemDO.class);	
 			// 检查是否已有此采购入库单的付款单草稿
			String oricode = request.getParameter("oriCode");
			SearchConditions scs = new SearchConditions();
			scs.addCondition("oricode", oricode, SearchCondition.OP_EQUAL);
			scs.addCondition("billstatus", "0", SearchCondition.OP_EQUAL);
			int fkcount = logicFkDAO.count(scs);
			if(fkcount > 0){
				throw new SyBaseException("已有此采购入库的付款单草稿，请先处理已有的单据");
			}		
			 
				String id = IDCodeTypeUtil.getId();
				curAP.setId(id);
				curAP.setFkCode(syCodeService.getCode("FK","FK",SyCode.DATE_YYMM,5));
				String fkcode = curAP.getFkCode();
				curAP.setBillStatus(0);
				curAP.setFkStatus(0);
				curAP.setDcruser(SessionUtil.getUser(request).getName());
				curAP.setDctime(new Date());
				if (fkDate != null && !"".equals(fkDate)) {
					curAP.setFkDate(DateUtils.stringToDate(fkDate));
				}	
				logicFkDAO.insertLogicFkDO(curAP);
				for (int i = 0; i < itemlist.size(); i++) {
					itemlist.get(i).setId(IDCodeTypeUtil.getId());
					itemlist.get(i).setFkid(id);
					itemlist.get(i).setFkcode(fkcode);
					logicFkItemDAO.insertLogicFkItemDO(itemlist.get(i));
				}
 			
		} catch (Exception e) {
			e.printStackTrace();
			throw new SyBaseException(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
	}
	
	@Override
	public void fkcommit(HttpServletRequest request, LogicFkDO curAP)
			throws SyBaseException, SyCodeException {
		try {
			String fkDate = request.getParameter("fkDate");
			String itemdata = request.getParameter("itemdata");	
			String itemdelete = request.getParameter("itemdelete");
			String powarecode = request.getParameter("oriCode");
 			List<LogicFkItemDO> itemlist = JSONArray.parseArray(itemdata, LogicFkItemDO.class);	
 			List<LogicPoWareDO> powarelist = new ArrayList<LogicPoWareDO>();
 			LogicPoWareDO pd = null;
 			Double presfhk = Double.parseDouble("0");  //本次实付货款
 			Double prewfhk = Double.parseDouble("0"); //本次未付货款
 			if (itemdelete != null && !"".equals(itemdelete)) {
				List<LogicFkItemDO> filist = JSONArray.parseArray(itemdelete, LogicFkItemDO.class);
				for (LogicFkItemDO fido : filist) {
					if (fido.getId() != null&& !"".equals(fido.getId())) {
						logicFkItemDAO.deleteLogicFkItemDOByPrimaryKey(fido.getId());
					}
				}
			}
 			//提交付款
 			if(itemlist != null && itemlist.size() > 0){
				for (LogicFkItemDO fkitem : itemlist) {
					fkitem.setYfhk((fkitem.getYfhk()==null ? 0 : fkitem.getYfhk()) + (fkitem.getSfhk()==null?0:fkitem.getSfhk()));
					fkitem.setWfhk((fkitem.getWfhk()==null ? 0 : fkitem.getWfhk()) - (fkitem.getSfhk()==null ? 0 : fkitem.getSfhk()));
					fkitem.setSfhk(fkitem.getSfhk()==null ? 0: fkitem.getSfhk());
					curAP.setYfhk((curAP.getYfhk()==null ? 0: curAP.getYfhk()) + fkitem.getSfhk());
					presfhk += fkitem.getSfhk();
					prewfhk += fkitem.getWfhk();
				}
			}
			curAP.setBillStatus(2);
			SearchConditions scs = new SearchConditions();
			scs.addCondition("powarecode", powarecode, SearchCondition.OP_EQUAL);
			scs.addCondition("billstatus","3,4,5", SearchCondition.OP_IN);
			powarelist = logicPoWareDAO.find(scs);
			if(powarelist!=null&&powarelist.size()>0){ //取得对应的采购入库单
				pd = powarelist.get(0);
			}
 			SearchConditions scs1 = new SearchConditions();
			scs1.addCondition("oricode", powarecode, SearchCondition.OP_EQUAL);
			scs1.addCondition("billstatus","2", SearchCondition.OP_EQUAL);
 			Double hisyfhk = logicFkDAO.findLastedDOByOricode(scs1);//最近一次付款后的已付金额	
 			Double hiswfhk = new Double("0.0");
 			
 			if(hisyfhk == null||hisyfhk==0){
 				hisyfhk = Double.parseDouble("0.0");
 			}
 			hiswfhk = new BigDecimal(curAP.getAmount().toString()).subtract(new BigDecimal(hisyfhk.toString())).doubleValue(); //最近一次收款后的未收金额
 			if(presfhk.doubleValue() < hiswfhk.doubleValue()) {
 				curAP.setFkStatus(1);
 				if(pd.getId()!=null){
 					pd.setFkstatus(1);  //根据收款情况改变销售出库单中的付款状态
 				}
 			} else if(presfhk.doubleValue() == hiswfhk.doubleValue()){
 				curAP.setFkStatus(2);
 				if(pd.getId()!=null){
 					pd.setFkstatus(2);
 				}
 			} else if(presfhk.doubleValue() > hiswfhk.doubleValue()) {
 				throw new SyBaseException("您本次付款大于付款单历史未付款！");
 			}
 			
 			int j = logicPoWareDAO.updateLogicPoWareDO(pd);
			if(j < 0){
				throw new SyBaseException("提交失败");
			}
			if (fkDate != null && !"".equals(fkDate)) {
				curAP.setFkDate(DateUtils.stringToDate(fkDate));
			}	
			
			curAP.setDuuser(SessionUtil.getUser(request).getName());
			curAP.setDutime(new Date());
			logicFkDAO.updateLogicFkDO(curAP);
			for (int i = 0; i < itemlist.size(); i++) {
				logicFkItemDAO.updateLogicFkItemDO(itemlist.get(i));
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new SyBaseException(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
	}

	@Override
	public Integer deleteBizRemoved(String id) throws SyBaseException {
		// TODO Auto-generated method stub
		return null;
	}

}
